package net.adst.util.fileFilters;

import net.adst.ui.mainframe.toppanel.ButtonsArea;

import javax.swing.*;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;

/**
 * Created with IntelliJ IDEA.
 * User: alekseipot
 * Date: 22.11.12
 * Time: 3:26
 * To change this template use File | Settings | File Templates.
 */
public class FileOutputStreamFactory {
    /**
     * This method is for creating a MSExcel file.
     *
     * @param file File, which we saving.
     * @return If extension equals ".xls" or ".xlsx" return FileOutputStream(file.getAbsoluteFile()).
     *         In other cases return FileOutputStream(file.getAbsoluteFile() + ".xlsx").
     */
    public static FileOutputStream getFileOutputStreamFromFactory(File file) {
        int position = file.getAbsoluteFile().toString().lastIndexOf(".");
        String str = file.getAbsoluteFile().toString().substring(position + 1);

        try {
            if (str.equals("xls")) {
                return new FileOutputStream(file.getAbsoluteFile());
            } else {
                return new FileOutputStream(file.getAbsoluteFile() + ".xls");
            }
        } catch (FileNotFoundException e) {
            int res = JOptionPane.showOptionDialog(null, "The file is already  used. Select another file or close all programs using this file.",
                    "The file is already  used.", JOptionPane.OK_CANCEL_OPTION, JOptionPane.WARNING_MESSAGE, null, null, null);
            if (res == JOptionPane.OK_OPTION) {
                ButtonsArea.saveNewExcelAction();
            } else {
                return null;
            }

//            e.printStackTrace();
        }
        return null;
    }
}
